package com.gitee.web.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

/**
 * AOP切面，动态切换数据源
 * @author thc
 */
@Component
@Aspect
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class DataSourceAspect {

    /**
     * 切面，需要加上fastmybatis自带的包：execution(* com.gitee.fastmybatis.core.support.*.*(..))
     */
    @Pointcut("execution(* com.gitee.web.service.*.*(..)) || execution(* com.gitee.fastmybatis.core.support.*.*(..))")
    public void aspect() {
    }


    @Before("aspect()")
    public void before(JoinPoint jp) throws Throwable {
        Object target = jp.getTarget();
        Class<?> clazz = target.getClass();
        DataSource anno = AnnotationUtils.findAnnotation(clazz, DataSource.class);
        if (anno != null) {
            DataSourceContextHolder.setDataSourceName(anno.value());
        } else {
            // 没有使用默认数据源
            String key = (String) DataSource.class.getMethod("value").getDefaultValue();
            DataSourceContextHolder.setDataSourceName(key);
        }
    }


}
